<?php

namespace app\api\controller;

use app\common\controller\Api;
// use app\admin\model\SurprisedGoods;
use think\Db;
/**
 *  惊喜订单
 *
 *  Author:  YSX
    Date:    2022-6-9
 */
class Surpriseorder extends Api
{
    // protected $noNeedLogin = ['goodsList'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }
    /*
     * 确认订单接口
    */
    public function confirm()
    {
        // $params = $this->params;
		if (!$this->request->isPost()) {
			return $this->error('提交方式不正确');
		}
		$params = $this->request->post();
		if(isset($params['cart_id'])){
			//从购物车下单
			$data = Db::name('surprised_cart as a')->where('a.id','in',$params['cart_id'])
				->join('surprised_goods x', 'a.surprised_goods_id = x.id')
				->join('surprised_goods_attr o', 'a.surprised_goods_attr_id = o.id')
			    ->field('a.id,a.number,x.goods_name,x.image,x.price,o.attr_name')
			    ->order('a.id desc')
			    ->select(); 
			foreach($data as $key => $value){
				$data[$key]['payMoney'] = $value['price'] * $value['number'];
			}
			if ($data) {
				$this->success('获取成功', $data);
			}
			$this->error('请求失败');
		}else{
			//直接支付去下单
			$where['is_del'] = array('eq',1);
			$where['is_enable'] = array('eq',1);
			$where['id'] = array('eq',$params['surprised_goods_id']);
			
			$goodsInfo = Db::name('surprised_goods')->field('id,goods_name,image,price')->where($where)->find();
			$goodsInfo['attr_name'] = Db::name('surprised_goods_attr')->where('id',$params['surprised_goods_attr_id'])->value('attr_name');
			$goodsInfo['payMoney'] = $params['number'] * $goodsInfo['price'];
			if ($goodsInfo) {
				$this->success('获取成功', $goodsInfo);
			}
			$this->error('请求失败');
		}
    }
	/*
	 * 下单接口
	*/
	public function confirmOrder()
	{
	    // $params = $this->params;
		if (!$this->request->isPost()) {
			return $this->error('提交方式不正确');
		}
		$params = $this->request->post();
		$userid = $this->auth->id;
		if(isset($params['cart_id'])){
			//查找用户地址信息
			$addressInfo = Db::name('member_address')->where('id',$params['address_id'])->find();
			//生成订单号
			$order_no = date('YmdHis', time()) . str_pad(mt_rand(1, 99999), 5, 0, STR_PAD_LEFT) . rand(1000, 99999);
			// \var_dump($pay_money);die;
			//启动事务
			Db::startTrans();
			try {
				$data = [
					'order_no' => $order_no,
					'member_id' => $userid,
					'mobile' => $addressInfo['mobile'],
					'username' => $addressInfo['username'],
					'province' => $addressInfo['province'],
					'city' => $addressInfo['city'],
					'county' => $addressInfo['county'],
					'address' => $addressInfo['address'],
					'housenumber' => $addressInfo['housenumber'],
					'address_id' => $params['address_id'],
					'pay_money' => 0,
					'status' => 1,
					'create_time' => time(),
				];
				$order_id = Db::name('surprised_order')->insertGetId($data);
				//从购物车下单
				$goodsInfo = Db::name('surprised_cart as a')->where('a.id','in',$params['cart_id'])
					->join('surprised_goods x', 'a.surprised_goods_id = x.id')
					->join('surprised_goods_attr o', 'a.surprised_goods_attr_id = o.id')
					->field('a.id,a.surprised_goods_id,a.surprised_goods_attr_id,a.number,x.goods_name,x.image,x.price,o.attr_name')
					->order('a.id desc')
					->select(); 
				$pay_money = 0;
				foreach($goodsInfo as $key => $value){
					$goods_data[$key]['order_id'] = $order_id;
					$goods_data[$key]['goods_id'] = $value['surprised_goods_id'];
					$goods_data[$key]['goods_attr_id'] = $value['surprised_goods_attr_id'];
					$goods_data[$key]['attr_name'] = $value['attr_name'];
					$goods_data[$key]['goods_name'] = $value['goods_name'];
					$goods_data[$key]['image'] = $value['image'];
					$goods_data[$key]['price'] = $value['price'];
					$goods_data[$key]['number'] = $value['number'];
					$goods_data[$key]['create_time'] = time();
					$pay_money += $value['price'] * $value['number'];
				}
				Db::name('surprised_order_goods')->insertAll($goods_data);
				//修改支付总价
				Db::name('surprised_order')->where('id',$order_id)->update(['pay_money'=>$pay_money]);
				//删除购物车信息晚点再写
				
				// 提交事务
				Db::commit();
				$res['order_no'] = $order_no;
				$res['pay_money'] = $pay_money;
			}catch (\Exception $e) {
				// \var_dump($e);
			    // 回滚事务
			    Db::rollback();
			}	
			if(isset($res['order_no'])){
				$this->success('下单成功', $res);
			}else{
				$this->error('下单失败');
			}
		}else{
			//查找商品信息
			$goodsInfo = Db::name('surprised_goods')->field('id,goods_name,image,price')->where('id',$params['surprised_goods_id'])->find();
			//查找用户地址信息
			$addressInfo = Db::name('member_address')->where('id',$params['address_id'])->find();
			$attr_name = Db::name('surprised_goods_attr')->where('id',$params['goods_attr_id'])->value('attr_name');
			//生成订单号
			$order_no = date('YmdHis', time()) . str_pad($params['surprised_goods_id'], 5, 0, STR_PAD_LEFT) . rand(1000, 99999);
			
			//启动事务
			Db::startTrans();
			try {
				// \var_dump($pay_money);die;
			    $data = [
			        'order_no' => $order_no,
			        'member_id' => $userid,
					'mobile' => $addressInfo['mobile'],
					'username' => $addressInfo['username'],
					'province' => $addressInfo['province'],
					'city' => $addressInfo['city'],
					'county' => $addressInfo['county'],
					'address' => $addressInfo['address'],
					'housenumber' => $addressInfo['housenumber'],
			        'address_id' => $params['address_id'],
			        'pay_money' => $goodsInfo['price'] * $params['number'],
			        'status' => 1,
			        'create_time' => time(),
			    ];
			    $order_id = Db::name('surprised_order')->insertGetId($data);
			
				//添加订单商品表
				$goods_data = [
				    'order_id' => $order_id,
				    'goods_id' => $goodsInfo['id'],
				    'goods_attr_id' => $params['goods_attr_id'],
				    'attr_name' => $attr_name,
				    'goods_name' => $goodsInfo['goods_name'],
				    'image' => $goodsInfo['image'],
				    'price' => $goodsInfo['price'],
				    'number'=>$params['number'],
				    'create_time' => time(),
				];
				Db::name('surprised_order_goods')->insert($goods_data);
			    // 提交事务
			    $result = Db::commit();
				$res['order_no'] = $order_no;
				$res['pay_money'] = $data['pay_money'];
			    
			}catch (\Exception $e) {
				// \var_dump($e);
			    // 回滚事务
			    Db::rollback();
			    // $this->error('下单失败');
			}
			if(isset($res['order_no'])){
				$this->success('下单成功', $res);
			}else{
				$this->error('下单失败');
			}
		}
	}
	/*
	 * 我的订单接口
	*/
    public function myOrder(){
	   // $params = $this->params;
	    if (!$this->request->isPost()) {
			return $this->error('提交方式不正确');
	    }
	    $params = $this->request->post();
		$userid = $this->auth->id;
	    $where['member_id'] = array('eq',$userid);
	    $where['is_del'] = array('eq',1);
	    if(isset($params['status']) && !empty($params['status'])){
			$where['status'] = array('eq',$params['status']);
			// $where[] = ['coupon_code_class_id', '=' , ];
	    }
	    $list = Db::name('surprised_order')->field('id,order_no,create_time,pay_money,status')->where($where)->order('id desc')->select();
	    if($list){
		    foreach($list as $key => $value){
			    $list[$key]['gooodsInfo'] = Db::name('surprised_order_goods')->field('id,goods_id,goods_attr_id,goods_name,attr_name,image,price,number')->where('order_id',$value['id'])->select();					
		    }
	    }
		$this->success('我的订单', $list);
    } 
	/*
	 * 订单详情
	*/
    public function orderDetail(){
		if (!$this->request->isPost()) {
			return $this->error('提交方式不正确');
		}
		$params = $this->request->post();
		$where['x.is_del'] = array('eq',1);
		if(isset($params['id']) && !empty($params['id'])){
			$where['x.id'] = array('eq',$params['id']);
		}
		//查找订单数据
		$info = Db::name('surprised_order')
			->alias('x')
			->join('member_address s', 's.id = x.address_id','left')
			->join('areas a', 's.province = a.id','left')
			->join('areas b', 's.city = b.id','left')
			->join('areas c', 's.county = c.id','left')
			->field('x.id,x.order_no,x.create_time,x.pay_money,x.status,x.address_id,s.*,a.name as province_name,b.name as city_name,c.name as county_name')
			->where($where)->find();
		$info['gooodsInfo'] = Db::name('surprised_order_goods')->field('id,goods_id,goods_attr_id,goods_name,attr_name,image,price,number')->where('order_id',$params['id'])->select();		
		$this->success('订单详情', $info);
	}
	/*
	 * 取消订单
	*/
	public function cancelOrder(){
		if (!$this->request->isPost()) {
			return $this->error('提交方式不正确');
		}
		$params = $this->request->post();
		$where['is_del'] = array('eq',1);
		if(isset($params['id']) && !empty($params['id'])){
			$where['id'] = array('eq',$params['id']);
		}
		//取消订单
		$result = Db::name('surprised_order')->where($where)->update(['status'=>5]);
		if ($result) {
			$this->success('取消成功');
		}
		$this->error('取消失败');
	}
	/*
	 * 删除订单
	*/
	public function delOrder(){
		if (!$this->request->isPost()) {
			return $this->error('提交方式不正确');
		}
		$params = $this->request->post();
		if(isset($params['id']) && !empty($params['id'])){
			$where['id'] = array('eq',$params['id']);
		}
		//取消订单
		$result = Db::name('surprised_order')->where($where)->update(['is_del'=>2]);
		if ($result) {
			$this->success('删除成功');
		}
		$this->error('删除失败');
	}
	/*
	 * 确认收货
	*/
	public function confirmReceipt(){
		if (!$this->request->isPost()) {
			return $this->error('提交方式不正确');
		}
		$params = $this->request->post();
		if(isset($params['id']) && !empty($params['id'])){
			$where['id'] = array('eq',$params['id']);
		}
		//把状态改成已完成
		$result = Db::name('surprised_order')->where($where)->update(['status'=>4]);
		if ($result) {
			$this->success('收货成功');
		}
		$this->error('收货失败');
	}
}
